<?php

namespace Zwwl2016\System;

use Illuminate\Console\Command;

class CreateCache extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:repo:makecache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'get cache code for commands';


    private $subUri;


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * @output String error_code 错误码;
     * @output String error_message 错误信息;
     * @return bool
     * @throws \ReflectionException
     */
    public function handle()
    {
		$folder="cmd_cache";
		is_dir($folder) OR mkdir($folder, 0777, true);
        $path = base_path('app/Console/Commands');
        $openDir = opendir($path);
        $artisan2='<?php
$arr = preg_split(\'/[ \.]/is\', microtime());
file_put_contents("time.txt",date("Y-m-d H:i:s").".".$arr[1]."\t",FILE_APPEND);
require_once \'vendor/autoload.php\';
require_once \'BaseCommand.php\';
';
		$baseCommandContent="<?php \n class BaseCommand { \n public function info(\$a) { \n echo json_encode(\$a); \n }\n }";
		is_file('BaseCommand.php') or file_put_contents('BaseCommand.php',$baseCommandContent);
        while ($file = readdir($openDir)){
            if($file != '.' && $file != '..'){
                list($className,$mime) = explode(".",$file);
                $content = file_get_contents($path.'/'.$file);
                preg_match("/protected \\$+signature = '[a-zA-Z\_]+(:[a-zA-Z\_]+)+( \\{\S+\\})*';/", $content,$matchSignature);
                if($matchSignature){
                    preg_match("/[a-zA-Z]+(\:[a-zA-Z]+)+/",$matchSignature[0],$match);
                    if($match){
                        $command = $match[0];
						$src='app/Console/Commands/'.$file;
						$desClass=str_replace(':','_',$command);
						$des=$folder."/".$desClass.".php";
						$desRequire=$folder."/"."__".$desClass.".php";
						$content = file_get_contents($src);
						$content =preg_replace('/namespace\s+App\\\Console\\\Commands\s*;/i', '', $content);
						$content =preg_replace('/use\s+Illuminate\\\Console\\\Command\s*;/i', '', $content);

						if(strtolower(substr($className, -6)) === 'common')
						{
							$content =preg_replace('/class\s+(\S+)\s+extends\s+Command/i', 'class '.$className.' extends BaseCommand', $content);
						}
						else
						{
							$content =preg_replace('/class\s+(\S+)\s+extends\s+Command/i', 'class '.$desClass.' extends BaseCommand', $content);
						}
						$content =preg_replace('/parent\s*::\s*__construct\(\)\s*;/i', '', $content);
						$content =preg_replace('/public\s+function\s+handle\(\)/i', 'public function handle($input_json)', $content);
						$content =preg_replace('/\$this\s*->\s*argument\s*\([0-9a-zA-Z\'"\s]+\)/i', '$input_json', $content);
						file_put_contents($des,$content);
                        if(strtolower(substr($className, -6)) === 'common')
						{
							$artisan2.="require_once '".$des."';\n";
						}
						  $class = new \ReflectionClass("App\Console\Commands\\".$className);
                        $comments = $class->getMethod('handle')->getDocComment();
                        $input=[];
						$contentRequire="";
						preg_match_all('/@dependence\s+(\S.*$)/i',$comments,$input);
						if(count($input)>1&&count($input[1])>0)
						{
							preg_match_all('/(\S+)\s*;/i',$input[1][0],$out);
							if(count($out)>1&&count($out[1])>0)
							{
								foreach($out[1] as $val)
								{
									$contentRequire.="require_once '".$folder."/".str_replace(':','_',$val).".php';\n";;
								}
							}
						}
						file_put_contents($desRequire,$contentRequire);
                    }else{
                        $response = ['error_code'=>'40000','error_message'=>'The signature of '.$className.' is not standard'];
                        $this->info(json_encode($response));
                        return false;
                    }
                }else{
                    $response = ['error_code'=>'40000','error_message'=>$className.' is not standard!'];
                    $this->info(json_encode($response));
                    return false;
                }
            }
        }
        $artisan2.='
$class=str_replace(":","_",$argv[1]);
include_once "cmd_cache/$class.php";
include_once "cmd_cache/__$class.php";
$obj=new $class();
if($argc<=3)
{
  $obj->handle($argv[2]);
}
else
{
  for($i=2;$i<$argc;$i++)
  {
    $obj->handle($argv[$i]);
    echo "\n";
    flush();
  }
}
$arr = preg_split(\'/[ \.]/is\', microtime());
file_put_contents("time.txt",date("Y-m-d H:i:s").".".$arr[1]."\t".$argv[1]."\n",FILE_APPEND);';
		file_put_contents('artisan2',$artisan2);
        $this->info(json_encode(['error_code'=>'0','error_message'=>'']));
        return true;
    }
}